package com.eicas.interceptor;

import com.eicas.Constant;
import com.eicas.ResultData;
import com.eicas.properties.CloudSecurityProperties;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.NonNull;
import org.apache.commons.codec.binary.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author: Administrator
 * @since: 2023/2/9 14:57
 * @description:
 */
@Component
public class ServerProtectInterceptor implements HandlerInterceptor {
    private CloudSecurityProperties properties;

    @Override
    public boolean preHandle(@NonNull HttpServletRequest request, @NonNull HttpServletResponse response, @NonNull Object handler){

        if (!properties.getOnlyFetchByGateway()) {
            return true;
        }
        String value = request.getHeader(Constant.GATEWAY_KEY);
        if (StringUtils.equals(Constant.SET_VALUE, value)) {
            return true;
        } else {
            ResultData resultData = new ResultData();
            resultData.setB(false);
            resultData.setStatus(HttpServletResponse.SC_FORBIDDEN);
            resultData.setMessage("请通过网关访问资源");
            writeJson(response,resultData);
            return false;
        }
    }

    private void writeJson(HttpServletResponse response, ResultData resultData) {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        PrintWriter out = null;
        try {
            out = response.getWriter();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        out.write(resultData.toString());
        out.flush();
        out.close();
    }

    public void setProperties(CloudSecurityProperties properties) {
        this.properties = properties;
    }
}
